import { defineStore } from 'pinia'
import type { TeachingPost, TeachingPostComment } from '../types/'

/**
 * 教学帖子存储模块
 * 负责管理教学交流帖子的全局状态
 */
export const useTeachingPostStore = defineStore('teachingPost', {
    state: () => ({
        // 所有帖子列表
        posts: [] as TeachingPost[],
        // 当前查看的帖子
        currentPost: null as TeachingPost | null,
        // 当前帖子的评论
        comments: [] as TeachingPostComment[],
        // 加载状态
        loading: false,
        // 搜索关键词
        searchKeyword: ''
    }),
    actions: {
        /**
         * 获取所有帖子
         */
        async fetchAllPosts() {
            this.loading = true
            try {
                // this.posts = await postApi.getAll()
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取帖子详情
         * @param postId - 帖子ID
         */
        async fetchPostDetail(postId: number) {
            this.loading = true
            try {
                // this.currentPost = await postApi.getDetail(postId)
                // this.comments = await postApi.getComments(postId)
            } finally {
                this.loading = false
            }
        },

        /**
         * 发布新帖子
         * @param newPost - 新帖子内容
         */
        async createPost(newPost: Omit<TeachingPost, 'postId' | 'createTime' | 'updateTime'>) {
            this.loading = true
            try {
                // const created = await postApi.create(newPost)
                // this.posts.unshift(created)
            } finally {
                this.loading = false
            }
        },

        /**
         * 添加评论
         * @param newComment - 新评论内容
         */
        async addComment(newComment: Omit<TeachingPostComment, 'id' | 'createTime'>) {
            this.loading = true
            try {
                // const created = await postApi.addComment({
                //     postId: this.currentPost!.postId,
                //     ...newComment
                // })
                // this.comments.push(created)
            } finally {
                this.loading = false
            }
        }
    },
    getters: {
        /**
         * 获取搜索筛选后的帖子
         */
        filteredPosts(state): TeachingPost[] {
            if (!state.searchKeyword.trim()) return state.posts
            const keyword = state.searchKeyword.toLowerCase()
            return state.posts.filter(post =>
                post.title.toLowerCase().includes(keyword) ||
                post.content.toLowerCase().includes(keyword))
        },

        /**
         * 获取热门帖子（按评论数排序）
         */
        popularPosts(state): TeachingPost[] {
            // 实际应用中可能需要从API获取
            return [...state.posts]
                // .sort((a, b) => b.commentCount - a.commentCount)
                .slice(0, 5)
        }
    }
})
